import { showToast } from "@/utils/index.js";
// const baseUrl = "http://106.15.8.119:12024/mjBoot";
const baseUrl = "https://hzlaba.top/mjBoot";

const httpInterceptor = {
  invoke(args) {
    // 拦截前触发,拼接url
    if (!args.url.startsWith("http")) {
      args.url = baseUrl + args.url;
    }

    //请求超时时间，默认60s
    args.timeout = 10000;

    //添加小程序请求头标志
    args.header = {
      ...args.header,
    };

    //添加token
    const token = uni.getStorageSync("token");
    if (token) {
      args.header["X-Access-Token"] = token;
    }
  },
};

// 添加拦截器
uni.addInterceptor("request", httpInterceptor);
uni.addInterceptor("uploadFile", httpInterceptor);

//定义泛型，接口返回的数据结构
const http = (options) => {
  return new Promise((resolve, reject) => {
    uni.request({
      ...options,
      // 响应成功
      success(res) {
        // 判断状态码
        if (res.statusCode == 200) {
          resolve(res.data); // 返回接口返回的数据
        } else if (res.statusCode == 401) {
          uni.removeStorageSync("token");
          uni.removeStorageSync("userInfo");
          showToast(`登陆失效，请重新登录！`);
          setTimeout(() => {
            if (uni.getStorageSync("roomID")) {
              uni.navigateTo({
                url: "/pages/login/index?id=" + uni.getStorageSync("roomID"),
              });
            } else {
              uni.navigateTo({
                url: "/pages/login/index",
              });
            }
          }, 2000);
        } else {
          showToast("服务器繁忙，请稍后再试");
        }
      },
      fail(err) {
        // 响应失败，网络错误，调用reject
        uni.showToast({
          title: "网络错误，换个网络试试",
          icon: "none",
        });
        reject(err);
      },
    });
  });
};

export default http;
